import CommonInput from "@/pages/OrderModule/common/components/CommonInput";
import CommonSelect from "@/pages/OrderModule/common/components/CommonSelect";
import CommonInputNumber from "@/pages/OrderModule/common/components/CommonInputNumber";
import { CommonModal } from "@/views/components/CommonModal";
import SubTitle from "@/pages/OrderModule/common/components/SubTitle";
import { Tooltip, Form, Select, Button, message } from "antd";
import { useState, useEffect } from "react";
import {
	queryExpressList,
	queryShopList,
	warehouseSelectList,
	expressStrategySaveOp,
	expressStrategyGetById,
	updateExpressStrategyOp
} from "../../service";
import CommonLoading from "@/components/CommonLoading";
import { isEmpty, isNil, find } from "lodash";
import SelectTag from "@/components/SelectTag";
import IconFont from "@/components/IconFont";
import SelectShop from "@/components/SelectShop";
import { labelTypeMap, labelColorMap } from "@/utils/config";
import { getAllowClearProps } from "../../helpers/constant";

const { Option } = Select;

//找，用，倉的渲染
const renderChannelIcon = flag => {
	if (flag == 1) {
		return (
			<span
				style={{
					display: "inline-block",
					width: "20px",
					height: "20px",
					lineHeight: "20px",
					borderRadius: "50%",
					backgroundImage: "linear-gradient(45deg, #0071F0, #5AA9FF)",
					color: "#fff",
					textAlign: "center",
					fontSize: "12px"
				}}
			>
				找
			</span>
		);
	} else if (flag == 2) {
		return (
			<span
				style={{
					display: "inline-block",
					width: "20px",
					height: "20px",
					lineHeight: "20px",
					borderRadius: "50%",
					backgroundImage: "linear-gradient(45deg, #981FDD, #CE6FFF)",
					color: "#fff",
					textAlign: "center",
					fontSize: "12px"
				}}
			>
				仓
			</span>
		);
	} else if (flag == 3) {
		return (
			<span
				style={{
					display: "inline-block",
					width: "20px",
					height: "20px",
					lineHeight: "20px",
					borderRadius: "50%",
					backgroundImage: "linear-gradient(45deg, #FF9000, #FFD285)",
					color: "#fff",
					textAlign: "center",
					fontSize: "12px"
				}}
			>
				用
			</span>
		);
	}
};

//弹窗标题
const titleMap = {
	add: "新增",
	edit: "编辑"
};

const AddIntelligentExpress = ({ visible, type, recordData, handleCancel, handleOk }) => {
	const [expressList, setExpressList] = useState([]); //快递列表
	const [ruleType, setRuleType] = useState(""); //快递规则的选择
	const [detailData, setDetailData] = useState({}); //详情数据
	const [warehouse, setWarehouse] = useState([]); //仓库下拉
	const [labelVisible, setLabelVisible] = useState(false); //是否展示标签弹窗
	const [selectLabels, setSelectLabels] = useState([]); //选择订单标签
	const [shopVisible, setShopVisible] = useState(false); //店铺组件弹窗
	const [selectShops, setSelectShops] = useState([]); //选择的店铺
	const [loading, setLoading] = useState(false);

	const [form] = Form.useForm();

	useEffect(() => {
		if (visible) {
			form.resetFields();
			setDetailData({});
			getExpressList();
			getWarehouseSelectList();
			setLabelVisible(false);
			if (!isEmpty(recordData)) {
				getExpressStrategyGetById();
				setRuleType(recordData.rule);
			}
		}
	}, [visible, recordData]);

	useEffect(() => {
		if (!isEmpty(detailData)) {
			form.resetFields();
			if (detailData.labelConfigList) {
				setSelectLabels(detailData.labelConfigList);
			}
			if (detailData.ecStoreList) {
				setSelectShops(detailData.ecStoreList);
			}
		}
	}, [detailData]);

	useEffect(() => {
		if (selectLabels.length) {
			form.setFieldsValue({
				labelIds: selectLabels.map(item => (labelTypeMap[item.name] ? labelColorMap[item.name] : item.name)).join(",")
			});
		} else {
			form.setFieldsValue({ labelIds: "" });
		}
	}, [selectLabels]);

	useEffect(() => {
		if (selectShops.length) {
			form.setFieldsValue({
				ecStoreIds: selectShops.map(item => (item.systemStoreName ? item.systemStoreName : item.storeName)).join(",")
			});
		} else {
			form.setFieldsValue({ ecStoreIds: "" });
		}
	}, [selectShops]);

	//智能快递详情
	const getExpressStrategyGetById = async () => {
		setLoading(true);
		setDetailData({});
		const { success, data = {} } = await expressStrategyGetById({
			id: recordData.id
		});
		if (success) {
			setDetailData(data);
		}
		setLoading(false);
	};

	//快递列表数据
	const getExpressList = async () => {
		setLoading(true);
		setExpressList([]);
		const { success, data } = await queryExpressList({ type: 1 });
		setLoading(false);
		if (success) {
			setExpressList(data);
		}
	};

	//仓库下拉选择
	const getWarehouseSelectList = async () => {
		setLoading(true);
		const { success, data = [] } = await warehouseSelectList();
		if (success) {
			setWarehouse(data);
		}
		setLoading(false);
	};

	//新增/编辑智能标签规则
	const saveNotAutoReviewStrategy = async val => {
		setLoading(true);
		let res;
		const params = {
			...val,
			ecStoreIds: selectShops.length > 0 ? selectShops.map(item => item.id).join(",") : undefined,
			labelIds: selectLabels.length > 0 ? selectLabels.map(item => item.id).join(",") : undefined
		};
		if (type == "add") {
			res = await expressStrategySaveOp(params);
		} else {
			params.id = recordData.id;
			res = await updateExpressStrategyOp(params);
		}
		const { success, msg = "" } = res;
		if (success) {
			message.success(msg);
			handleOk();
		}
		setLoading(false);
	};

	const onFinish = values => {
		form
			.validateFields()
			.then(val => {
				saveNotAutoReviewStrategy(val);
			})
			.catch(err => {});
	};

	const onFinishFailed = errorInfo => {
		console.log("Failed:", errorInfo);
	};

	//清除店铺/标签弹窗
	const handleClear = (e, code) => {
		const val = e.target.value;
		if (val == "") {
			if (code == "store") {
				setSelectShops([]);
			} else {
				setSelectLabels([]);
			}
		}
	};

	//标签弹窗
	const SelectTagProps = {
		selectLabels: selectLabels.map(item => item.id),
		showFilterMethod: false,
		handleCancel() {
			setLabelVisible(false);
		},
		handleDealData(selectTag, realData) {
			const arr = [];
			selectTag.forEach(item => {
				const obj = find(realData, ["id", item]);
				arr.push(obj);
			});
			return arr;
		},
		handleOK(val) {
			setLabelVisible(false);
			setSelectLabels(val);
		}
	};

	//店铺组件
	const SelectShopProps = {
		selectShops: selectShops.map(item => item.id),
		handleCancel() {
			setShopVisible(false);
		},
		handleOk(arr) {
			setShopVisible(false);
			setSelectShops(arr);
		}
	};

	//仓库下拉多选
	const optionWarehouse =
		!isEmpty(warehouse) &&
		warehouse.map(d => (
			<Option key={d.id} value={d.id + ""}>
				{d.warehouseName}({d.isOpen ? "代发" : "自发"})
			</Option>
		));

	return (
		<>
			<CommonModal
				title={{ title: `${titleMap[type]}智能快递` }}
				open={visible}
				onCancel={handleCancel}
				width={434}
				bodyStyle={{ height: 460, overflow: "hidden" }}
				okText="保存"
				footer={[
					<Button key="back" onClick={handleCancel}>
						取消
					</Button>,
					<Button disabled={type == "view"} key="save" htmlType="submit" onClick={onFinish} type="primary">
						保存
					</Button>
				]}
			>
				<Form
					name="basic"
					onFinish={onFinish}
					onFinishFailed={onFinishFailed}
					autoComplete="off"
					layout="horizontal"
					labelAlign="right"
					form={form}
					initialValues={{
						...detailData,
						warehouseIds: detailData.warehouseIds ? detailData.warehouseIds + "" : undefined
					}}
				>
					<SubTitle title="基本信息" as="s2" symbol />
					<Form.Item name="name" rules={[{ required: true, message: "必填，请输入智能快递规则名称" }]} style={{ marginTop: 16 }}>
						<CommonInput placeholder="必填，请输入智能快递规则名称" maxLength={30} showCount aria-required allowClear />
					</Form.Item>
					<Form.Item
						name="level"
						rules={[
							{ required: true, message: "必填，请输入优先级" },
							{
								pattern: /^[1-9]\d*$/g,
								message: "请输入正整数"
							}
						]}
					>
						<CommonInputNumber placeholder="必填，优先级" aria-required min={1} max={100} allowClearProps={getAllowClearProps(form)} />
					</Form.Item>

					<SubTitle title="处理方式" as="s2" symbol />
					<Form.Item rules={[{ required: true, message: "必填，请选择快递规则" }]} name="rule" style={{ marginTop: 16 }}>
						<CommonSelect aria-required onChange={e => setRuleType(e)} value={ruleType} placeholder="请选择快递规则" allowClear>
							<Option value={1}>指定快递</Option>
							<Option value={2}>价格最低</Option>
						</CommonSelect>
					</Form.Item>
					{ruleType == 1 && (
						<Form.Item rules={[{ required: true, message: "必填，请选择快递" }]} name="expressId">
							<CommonSelect allowClear aria-required placeholder="请选择快递">
								{expressList.length &&
									expressList.map(function (item) {
										return (
											<Option value={item.baseExpressId} key={item.id}>
												<Tooltip title={item.baseExpressName}>
													<span>{item.baseExpressName}</span>
													{renderChannelIcon(item.expressFlag)}
												</Tooltip>
											</Option>
										);
									})}
							</CommonSelect>
						</Form.Item>
					)}
					<SubTitle
						title={
							<>
								订单条件
								<span style={{ fontWeight: 300, fontSize: 12 }}>（不同条件之间需要都满足）</span>
							</>
						}
						as="s2"
						symbol
					/>
					<Form.Item name="ecStoreIds" style={{ marginTop: 16 }}>
						<CommonInput
							// {...inputProps}
							allowClear
							onChange={e => handleClear(e, "store")}
							onClick={() => setShopVisible(true)}
							placeholder="请选择店铺"
							// readOnly
							suffix={<IconFont onClick={() => setShopVisible(true)} style={{ cursor: "pointer" }} type="iconmodal-input" />}
						/>
					</Form.Item>
					<Form.Item name="labelIds">
						<CommonInput
							// readOnly
                            allowClear
							onChange={e => handleClear(e, "orderTag")}
							onClick={() => setLabelVisible(true)}
							placeholder="请选择订单标签"
							suffix={<IconFont onClick={() => setLabelVisible(true)} style={{ cursor: "pointer" }} type="iconmodal-input" />}
						/>
					</Form.Item>
					<Form.Item name="warehouseIds">
						<Select showSearch placeholder="请选择仓库" optionFilterProp="children" allowClear={true}>
							{optionWarehouse}
						</Select>
					</Form.Item>
				</Form>
				{labelVisible && <SelectTag {...SelectTagProps} />}
				{shopVisible && <SelectShop {...SelectShopProps} />}
				<CommonLoading loading={loading} />
			</CommonModal>
		</>
	);
};
export default AddIntelligentExpress;
